import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-05-18
 * Time: 22:53
 */
public class TestUdpEchoSever {

    private DatagramSocket socket = null;

    public TestUdpEchoSever(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");
        // 服务器不停的处理
        while (true) {
            // 1. 接收客户端请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket);// requestPacket输出型参数
            // 2. 处理客户端请求并返回相应信息
            // 为方便处理请求，将请求信息构造成字符串
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            // 接收处理后的相应信息
            String response = process(request);
            // 3. 将处理完成的响应信息发送给客户端
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);
            // 为方便查看，这里打印一下日志：服务器ip+服务器端口号+请求信息+响应信息
            System.out.printf("ClientIP:%s ClientPort:%d request:%s response:%s\n",requestPacket.getAddress(),requestPacket.getPort(),
                    request,response);
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TestUdpEchoSever testUdpEchoSever = new TestUdpEchoSever(9090);
        testUdpEchoSever.start();
    }
}
